package com.meitianhui.convenitenbuy.module.order.ui.fragment;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseFragment;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.order.adapter.FightGroupOrderAdapter;
import com.meitianhui.convenitenbuy.module.order.contract.EdinburghTypeOrderContract;
import com.meitianhui.convenitenbuy.module.order.di.DaggerOrderComponent;
import com.meitianhui.convenitenbuy.module.order.di.OrderModule;
import com.meitianhui.convenitenbuy.module.order.model.bean.OrderInfo;
import com.meitianhui.convenitenbuy.module.order.presenter.EdinburghTypeOrderPresenter;
import com.meitianhui.convenitenbuy.module.order.ui.activity.FightGroupOrderDetailActivity;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.CustomTipDialog;
import com.meitianhui.convenitenbuy.widget.dialog.LoadingDialog;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.meitianhui.convenitenbuy.Constants.MEMBER_TYPE_KEY;

/**
 * Created by Administrator on 2017/11/16.
 * 拼团领
 */

public class FightGroupOrderFragment extends BaseFragment implements EdinburghTypeOrderContract.View,SwipeRefreshLayout.OnRefreshListener{
    public static final String Tag = FightGroupOrderFragment.class.getSimpleName();
    private int mPageIndex = 1;
    private int mPageSize = 15;
    private FightGroupOrderAdapter mAdapter;
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mSwipeLayout;
    private View mNotDataView;
    private String mService = "tsOrder.consumer.tsOrderListPageFind";
    private LoadingDialog mDialog;
    private CustomTipDialog mODialog = null;
    private int mOrderStatus = 0;   //0 取消订单  1 提交订单
    @Inject
    EdinburghTypeOrderPresenter presenter;
    @Override
    protected int getLayout() {
        return R.layout.fragment_fight_group_order;
    }

    @Override
    protected void initView(LayoutInflater inflater) {
        super.initView(inflater);
        DaggerOrderComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .orderModule(new OrderModule(this))
                .build()
                .inject(this);
        mSwipeLayout = (SwipeRefreshLayout) getViewById(R.id.swipe_layout);
        mSwipeLayout.setOnRefreshListener(this);
        mRecyclerView = (RecyclerView) getViewById(R.id.rv_fight_group_order);
        LinearLayoutManager lManager = new LinearLayoutManager(getActivity());
        lManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(lManager);
        mNotDataView = getActivity().getLayoutInflater().inflate(R.layout.data_empty_order, (ViewGroup) mRecyclerView.getParent(), false);
        initData();
    }

    private void initData(){
        mAdapter = new FightGroupOrderAdapter(getActivity(), null, null, new FightGroupOrderAdapter.OnClickOrder() {
            @Override
            public void cancelClick(String orderId) {
                mODialog = new CustomTipDialog(getActivity(), new CustomTipDialog.DialogClick() {
                    @Override
                    public void cancelClick() {
                        mODialog.stopProgressDialog();
                    }
                    @Override
                    public void submitClick() {
                        mOrderStatus = 0;
                        String content = mODialog.getContent();
                        if(TextUtils.isEmpty(content)){
                            TipUtils.showToast(App.getInstance(), "请输入取消订单的理由");
                        }else{
                            presenter.orderOperation(orderId,"tsOrder.consumer.tsOrderCancel",content,"", Constants.CUSTOM_APP);
                            mODialog.stopProgressDialog();
                        }
                    }
                });
                mODialog.setTitle("提示");
                mODialog.setVisible(true);
                mODialog.setContent("取消订单款项将返还至您的账户，确定取消？");
            }

            @Override
            public void confirmClick(String orderId) {
                mODialog = new CustomTipDialog(getActivity(), new CustomTipDialog.DialogClick() {
                    @Override
                    public void cancelClick() {
                        mODialog.stopProgressDialog();
                    }

                    @Override
                    public void submitClick() {
                        mOrderStatus = 1;
                        presenter.orderOperation(orderId,"tsOrder.consumer.tsOrderReceived","","", Constants.CUSTOM_APP);
                    }
                });
                mODialog.setTitle("提示");
                mODialog.setContent("是否确认收货");
            }

            @Override
            public void detailClick(String orderId,String activityId) {
                Intent intent = new Intent(getActivity(),FightGroupOrderDetailActivity.class);
                intent.putExtra("order_id",orderId);
                intent.putExtra("activity_id",activityId);
                startActivity(intent);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        if(mDialog==null){
            mDialog = new LoadingDialog(getActivity());
        }
        registerPush();
        onRefresh();
    }


    private void registerPush() {
        Disposable subscribe = RxBus.get().toFlowable(EventBean.class).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean bean) throws Exception {
                if (bean != null) {
                    if (bean.type == Constants.EVENT_TYPE_LOGIN_SUCCESS) {
                        onRefresh();
                    }
                }
            }
        });
        mCompositeDisposable.add(subscribe);
    }

    @Override
    public void onRefresh() {
        mPageIndex = 1;
        presenter.getOrder(mService,mPageIndex + "", mPageSize + "",MEMBER_TYPE_KEY, "");
    }


    @Override
    public void showError(String msg) {

    }

    @Override
    public void getOrderSuccess(OrderInfo orderInfo) {
        if(mDialog!=null){
            mDialog.stopProgressDialog();
        }
        mSwipeLayout.setRefreshing(false);
        setData(mPageIndex,orderInfo.getList(),orderInfo.getDoc_url());
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPageIndex++;
                presenter.getOrder(mService,mPageIndex + "", mPageSize + "",MEMBER_TYPE_KEY, "");
            }
        },mRecyclerView);

    }

    @Override
    public void getOrderFail(int code, String msg) {
        if(mDialog!=null){
            mDialog.stopProgressDialog();
        }
        if(mPageIndex==1){
            mAdapter.setEmptyView(mNotDataView);
        }
        mSwipeLayout.setRefreshing(false);
    }

    private void setData(int pageIndex,List data,Map<String, String> map) {
        final int size = data == null ? 0 : data.size();
        if(pageIndex==1){
            mAdapter.setNewData(data,map);
            if(size==0){
                mAdapter.setEmptyView(mNotDataView);
            }
        }else{
            if(size>0){
                mAdapter.addData(data,map);
            }
        }
        if (size < mPageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(false);
        } else {
            mAdapter.loadMoreComplete();
        }

    }
    @Override
    public void orderOperationSuccess() {
        if (mOrderStatus == 1) {
            TipUtils.showToast(App.getInstance(), "确认订单成功");
        } else {
            TipUtils.showToast(App.getInstance(), "取消订单成功");
        }
        onRefresh();
        RxBus.get().post(new EventBean(Constants.EVENT_TYPE_ORDER_OPERATION));
    }

    @Override
    public void orderOperationFail(int code, String msg) {

    }


    @Override
    public void call(Object o) {

    }
}
